package com.example.utrl;

import org.apache.commons.dbcp2.BasicDataSource;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.*;

/**
 * @author ：lqs
 * @date ：Created in 2023/8/30 11:42
 * @description：
 * @modified By：
 * @version:
 */
public class BaseDao {
    private static String DRIVER_CLASS;
    private static String DB_URL;
    private static String DB_USER;
    private static String DB_PASS;

    private static int DB_MINIdLE;
    private static int DB_MAXIdLE;

    public static void main(String[] args) {

    }

    static {
        //  创建 Properties 对象
        Properties properties = new Properties();
        //  读取 Properties 属性文件到输入流中
        InputStream resourceAsStream = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
        //  从输入流中加载属性列表
        try {
            properties.load(resourceAsStream);
            DRIVER_CLASS = properties.getProperty("driver");
            DB_URL = properties.getProperty("url");
            DB_USER = properties.getProperty("user");
            DB_PASS = properties.getProperty("password");
            DB_MINIdLE = Integer.valueOf(properties.getProperty("minIdle"));
            DB_MAXIdLE = Integer.valueOf(properties.getProperty("maxIdle"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //  加载驱动
    static {
        try {
            Class.forName(DRIVER_CLASS);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }


    /**
     * @return java.sql.Connection
     * @create by: 陈海彬
     * @description: 通过连接处创建连接对象
     * @create time: 2023/8/23 15:08
     */
    private static Connection getConnection() {
        //  创建连接池
        BasicDataSource dataSource = new BasicDataSource();
        Connection connection = null;
        try {
            dataSource.setUrl(DB_URL);
            dataSource.setUsername(DB_USER);
            dataSource.setPassword(DB_PASS);
            dataSource.setMinIdle(DB_MINIdLE);
            dataSource.setMaxIdle(DB_MAXIdLE);
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return connection;
    }

    /**
     * @param connection
     * @param statement
     * @param resultSet
     * @return void
     * @create by: 陈海彬
     * @description: 关闭连接，释放资源
     * @create time: 2023/8/23 15:09
     */
    private static void closeConnection(Connection connection, Statement statement, ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param ps
     * @param params
     * @return java.sql.PreparedStatement
     * @create by: 陈海彬
     * @description: 设置占位符
     * @create time: 2023/8/23 15:10
     */
    private static PreparedStatement setParams(PreparedStatement ps, Object... params) {
        if (params != null && params.length > 0) {
            for (int i = 0; i < params.length; i++) {
                try {
                    ps.setObject(i + 1, params[i]);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return ps;
    }

    /**
     * @param sql
     * @param params
     * @return boolean
     * @create by: 陈海彬
     * @description: 通用的修改方法
     * @create time: 2023/8/23 15:12
     */
    public boolean executeUpdate(String sql, Object... params) {
        //  创建连接对象
        Connection connection = getConnection();
        PreparedStatement ps = null;
        try {
            ps = connection.prepareStatement(sql);
            //  设置占位符
            ps = setParams(ps, params);
            //  影响的行数
            int index = ps.executeUpdate();
            if (index > 0) {
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeConnection(connection, ps, null);
        }
        return false;
    }

    /**
     * @param sql
     * @param params
     * @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @create by: 陈海彬
     * @description: 通用的查询方法
     * @create time: 2023/8/23 15:15
     */

    public List<Map<String, Object>> executeQuery(String sql, Object... params) {
        //  创建连接对象
        Connection connection = getConnection();
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        try {
            ps = connection.prepareStatement(sql);
            //  设置占位符
            ps = setParams(ps, params);
            //  执行语句
            resultSet = ps.executeQuery();
            //  获取元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            //  获取影响的行数
            int count = metaData.getColumnCount();
            List<Map<String, Object>> mapList = new ArrayList<>();
            //  移动游标
            while (resultSet.next()) {
                Map<String, Object> map = new HashMap<>();
                for (int i = 1; i <= count; i++) {
                    //  获取key
                    String columnName = metaData.getColumnName(i);
                    Object columnValue = resultSet.getObject(columnName);
                    map.put(columnName, columnValue);
                }
                mapList.add(map);
            }
            return mapList;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeConnection(connection, ps, resultSet);
        }
        return null;
    }



}
